package com.example.common.common.config.llm;

import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.common.utils.RedisUtils;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author qwert
 * @version 1.0.0
 * @create 2025/8/7 23:33
 **/
@Component
public class RedisMemoryRepository implements ChatMemory {

    @Autowired
    private RedisUtils redisUtils;

    private static final String CHAT_HISTORY_KEY_PREFIX = "chat:history:";

    @Override
    public void add(String conversationId, List<Message> messages) {
        if (conversationId == null || messages == null || messages.isEmpty()) {
            return;
        }

        String key = CHAT_HISTORY_KEY_PREFIX + conversationId;
        boolean hasKey = redisUtils.hasKey(key);

        List<Message> existing;
        if (!hasKey) {
            existing = messages;
        } else {
            existing = JSONObject.parseObject(redisUtils.get(key), new TypeReference<>() {
            });
            existing.addAll(messages);
        }

        redisUtils.set(key, JSONObject.toJSONString(existing), 1L, TimeUnit.DAYS);
    }

    @Override
    public List<Message> get(String conversationId) {
        if (conversationId == null) {
            return Collections.emptyList();
        }

        String key = CHAT_HISTORY_KEY_PREFIX + conversationId;
        boolean hasKey = redisUtils.hasKey(key);
        if (!hasKey) {
            return Collections.emptyList();
        }
        List<Message> messages = JSONObject.parseObject(redisUtils.get(key), new TypeReference<>() {
        });

        return messages != null ? messages : Collections.emptyList();
    }

    @Override
    public void clear(String conversationId) {
        if (conversationId == null) {
            return;
        }

        String key = CHAT_HISTORY_KEY_PREFIX + conversationId;
        redisUtils.delete(key);
    }
}